package com.chenjinlong.servlet;

import com.chenjinlong.model.TodoItem;
import com.chenjinlong.until.DBUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

@WebServlet("/list")
public class ListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、从数据库中查出List<待办事项>todolist
        List<TodoItem> todolist = new ArrayList<>();
        try (Connection c = DBUtil.connection()){
            String sql = "SELECT id,todo,state FROM item ORDER BY id";
            try(PreparedStatement s = c.prepareStatement(sql)){
                try (ResultSet rs = s.executeQuery()){
                    while(rs.next()){
                        TodoItem todo = new TodoItem();
                        todo.id = rs.getInt("id");
                        todo.todo = rs.getString("todo");
                        todo.state = rs.getBoolean("state");

                        todolist.add(todo);
                    }
                }
            }
        } catch (SQLException exc) {
            throw new ServletException(exc);
        }

        //2、把todolist序列化成JSON格式的字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(todolist);
        //3、进行响应输出
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(s);

    }
}
